package com.thestore.h5tool;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.json.JSONException;
import org.json.JSONObject;

import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.MenuItem;
import com.google.gson.JsonIOException;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.thestore.main.component.dailog.DialogUtil;
import com.thestore.main.component.dailog.UiUtil;
import com.thestore.main.component.dailog.DialogUtil.PositiveButtonClickListener;
import com.thestore.main.component.dailog.DialogUtil.SingleItemsButtonClickListener;
import com.thestore.main.core.app.AppContext;
import com.thestore.main.core.datastorage.DataHelper;
import com.thestore.main.core.datastorage.bean.Settings;
import com.thestore.main.core.datastorage.bean.UserInfo;
import com.thestore.main.core.log.Lg;
import com.thestore.main.core.net.cache.CacheMgr;
import com.thestore.main.core.net.request.UrlHelper;
import com.yhdplugin.app.MyApplication;
import com.yhdplugin.loader.PluginUpdateCallBack;

import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.text.format.DateFormat;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class MainActivity extends SherlockFragmentActivity {

	private List<H5Data> mdatas;;
//	private PullToRefreshListView listView;
	//private GetDataTask dataHandler;
//	private ListView listView_in;
	private H5Adapter adpater;
	private UiUtil uiUtil;
	private ListView mListView = null;
	private static final String NOCLICK = ",FFF,global,";
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//正式发布要放在loading activity里
		//MyApplication.instance().InitPlugin();
		setContentView(R.layout.activity_h5list);
		//setActionBarTitle("H5 APP辅助开发工具");
		uiUtil = new UiUtil(this);
		mdatas = new ArrayList<H5Data>();
		getSupportActionBar().setHomeButtonEnabled(true);
		mListView = (ListView) findViewById(R.id.demo_list);
		
//		listView = (PullToRefreshListView)findViewById(R.id.pull_refresh_list);
//		listView.setMode(Mode.PULL_FROM_START);
//		listView.setShowIndicator(false);
//		listView_in = listView.getRefreshableView();
		//listView_in.setAdapter(adapter);

		//		adapter = new NetBeanAdapter.Builder(TopicData.class, "http://www.baidu.com", this, R.layout.list_item_topic)
		//		.setListDataKey("topics").setPageSize(10).setPageParams("p")
		//		.setPageSizeParams("pagesize").create();
		//		//add some bind relation
		//		adapter.addField("title", R.id.title);
//		listView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
//
//			@Override
//			public void onPullDownToRefresh(
//					PullToRefreshBase<ListView> refreshView) {
//				String label = "上次更新:" + DateFormat.format("yyyy年MM月dd日 kk:mm", new Date());
//				// Update the LastUpdatedLabel  
//				refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);  
//				//				new Thread(new Runnable() {
//				//					@Override
//				//					public void run() {
//				//						try {
//				//							Thread.sleep(3000);
//				//							runOnUiThread(new Runnable() {
//				//								@Override
//				//								public void run() {
//				//									listView.onRefreshComplete();
//				//								}
//				//							});
//				//						} catch (InterruptedException e) {
//				//							e.printStackTrace();
//				//						}
//				//					}
//				//				}).start();
//				dataHandler.execute();
//
//			}
//
//			@Override
//			public void onPullUpToRefresh(
//					PullToRefreshBase<ListView> refreshView) {
//				// TODO Auto-generated method stub
//
//			}
//		});
//
//		listView_in.setOnItemClickListener(new OnItemClickListener() {
//
//			@Override
//			public void onItemClick(AdapterView<?> parent, View view,
//					int position, long id) {
//				// TODO Auto-generated method stub
//				//mydialog.showToastLong(BBSList.this, ""+position);
//				H5Data data = (H5Data)adpater.getItem(position-1);
//			    Map<String,String> p = new HashMap<String,String>();
//			    p.put("id", data.get_h5id());
//				startActivity(AppContext.getUrlIntent("yhd://localweb/", "", null));
//			}
//		});
		mListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				H5Data data = mdatas.get(position);
				HashMap<String,String> p = new HashMap<String,String>();
			    p.put("path", data.get_h5id());
			    if(NOCLICK.indexOf(data.get_h5id()) >= 0 )
			    {
			      Toast.makeText(MainActivity.this, "公共JS模块，不能预览!", Toast.LENGTH_LONG).show();
			    }
			    else
			    {
				  startActivity(AppContext.getUrlIntent("yhd://localweb/", "", p));
			    }
			}
		});
	}


	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		showProgress();
		GetDataTask dataHandler = new GetDataTask();
		dataHandler.execute();
	}
	private class GetDataTask extends AsyncTask<Void, Void, List<H5Data>> {

		@Override
		protected List<H5Data> doInBackground(Void... params) {
			// Simulates a background job.
			List<H5Data> temp = new ArrayList<H5Data>();
			File f = new File(AppContext.APP.getFilesDir(),"h5content");
			File data = new File(f,"cfg.txt");
			if(data.exists())
			{
				try {
					HashMap<String, String> htdata = DataHelper.gson.fromJson(
							new InputStreamReader(new FileInputStream(data)),
							new TypeToken<HashMap<String, String>>() {
							}.getType());
					Iterator<Entry<String, String>> iter = htdata.entrySet().iterator();
					while (iter.hasNext()) {
						Map.Entry<String,String> entry = (Map.Entry<String,String>) iter.next();
						H5Data tdata = new H5Data();
						tdata.set_h5id(entry.getKey());
						tdata.set_version(entry.getValue());
						temp.add(tdata);
					}

				} catch (JsonIOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (JsonSyntaxException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			return temp;
		}

		@Override
		protected void onPostExecute(List<H5Data> rst) {
			mdatas = rst;
			if(adpater == null)
			{
				adpater = new H5Adapter(mdatas, MainActivity.this);
				mListView.setAdapter(adpater);
				cancelProgress();
			}
			else
			{
				adpater.replaceAll(rst);
				cancelProgress();
				//listView.onRefreshComplete();
			}
			
			super.onPostExecute(rst);
		}
	}
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if(keyCode == KeyEvent.KEYCODE_BACK)
		{
			ActivityManager activityManager = (ActivityManager) this
					.getSystemService(Context.ACTIVITY_SERVICE);
			activityManager.restartPackage(this.getPackageName());
		}
		//System.gc();
		System.exit(0);
		finish();
		return super.onKeyDown(keyCode, event);
	}

	private void showProgress()
	{
		uiUtil.showProgress();
	}
	
	private void cancelProgress()
	{
		uiUtil.cancelProgress();
	}
	
	 

	@Override
	public boolean onCreateOptionsMenu(com.actionbarsherlock.view.Menu menu) {
		// TODO Auto-generated method stub
		getSupportMenuInflater().inflate(R.menu.topmenu, menu);    
		return super.onCreateOptionsMenu(menu);
	}


	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch(item.getItemId()){    
        case R.id.menu_delete: 
        	
        	showChooseServer();
            //Toast.makeText(this, "delete", Toast.LENGTH_SHORT).show();    
            break;    
          
        }    
		return super.onOptionsItemSelected(item);
	}


	private void showChooseServer() {
		DialogUtil.showDialogSingleChoice(
				this,
				getString(R.string.home_choose_server),
				-1,
				getResources().getStringArray(R.array.loading_server),
				new SingleItemsButtonClickListener() {
					@Override
					public void setSingleChoiceItems(DialogInterface dialog,
							int index) {
						String ip = getResources().getStringArray(
								R.array.loading_ip)[index];

						Lg.d(Settings.getDomainForDebug(), ip);

						if (!Settings.getDomainForDebug().equals(ip)) {

							Settings.setDomainForDebug(ip);

							// 切环境以后要清除url和接口数据缓存
							UrlHelper.clearUrlCache();
							//js接口暂时不能设置缓存
							//CacheMgr.clearCache();
							UserInfo.clearAll();

						}
						// 切环境以后刷新key
						AppContext.resetKey();
					}
				}, "退出",
				new PositiveButtonClickListener() {
					@Override
					public void setPositiveButton(DialogInterface dialog,
							int index) {
						dialog.dismiss();;
					};
				});
	}
}
